<div class="row">
    <div class="col-xs-12">
        <div class="panel">
            <a href="#addContentCategory" role="button" class="btn btn-primary btn-sm" data-toggle="modal"><span class="fa fa-plus-square" aria-hidden="true">&nbsp;</span>增加顶级分类</a>
        </div>
        <div class="box">
            <div class="box-body" >
                <div class="zTreeDemoBackground left">
                    <ul id="categoryTree" class="ztree"></ul>
                </div>
            </div><!-- /.box-body -->
        </div><!-- /.box -->

    </div><!-- /.col -->
    <!--信息提示模态窗口-->
    <div class="modal fade" id="checkIfDel">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">系统提示</h4>
                </div>
                <div class="modal-body">
                    <div class="text-danger"><i class="icon fa fa-warning"></i> 确认删除该条记录？</div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" ng-click="delCategoryItem()">删除</button>
                    <button type="button" class="btn btn-primary" data-dismiss="modal">取消</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

    <!--添加用户组模态窗口-->
    <div class="modal fade" id="addContentCategory">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">添加文档类别</h4>
                </div>
                <div class="modal-body">
                    <form role="form" class="form-horizontal" name="myForm" ng-submit="processForm(myForm.$valid)" novalidate>
                        <div class="form-group">
                            <label class="control-label col-sm-4">父类别</label>
                            <div class="col-sm-4">
                                <!--<input type="text" class="form-control" name="name" ng-model="formData.parentID" disabled/>-->
                                <p class="form-control-static text-primary">{{formData.parentID}}</p>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-4">类别名称</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" name="name" ng-model="formData.name" ng-minlength="2" ng-maxlength="12" required/>
                                <label for="inputError" class="control-label text-danger" ng-show="myForm.name.$invalid && !myForm.name.$pristine"><i class="fa fa-times-circle-o"></i> 2-12个非特殊字符</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-4">是否隐藏栏目</label>
                            <div class="radio col-sm-4">
                                    <label>
                                        <input type="radio" class="mini" name="state" value="1" ng-model="formData.state" checked/>显示&nbsp;
                                    </label>
                                    <label>
                                        <input type="radio" class="mini" name="state" value="0" ng-model="formData.state"/>隐藏
                                    </label>

                            </div>
                        </div>
                        <div class="form-group" id="setCateTemp">
                            <label class="control-label col-sm-4">板块模板</label>
                            <div class="col-sm-5">
                                <div class="dropdown">
                                    <button id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                        <i id="tempsName">请选择内容模板</i>
                                        <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel" id="treeDemo" class="ztree">
                                        <li role="presentation"><a href="#">test</a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="form-group" id="defaultUrl">
                            <label class="control-label col-sm-4">URL</label>
                            <div class="col-sm-6">
                                <input type="text" class="form-control" name="homePage" ng-model="formData.homePage" placeholder="由关键字组成的链接字符串" ng-minlength="2" ng-maxlength="30" ng-pattern="/^\S+[a-z A-Z]$/" required/>
                                <label for="inputError" class="control-label text-danger" ng-show="myForm.homePage.$invalid && !myForm.homePage.$pristine"><i class="fa fa-times-circle-o"></i> 2-30个英文字符</label>

                            </div>
                        </div>
                        <div class="form-group" id="setCateSort">
                            <label class="control-label col-sm-4">排序</label>
                            <div class="col-sm-2">
                                <input type="text" class="form-control" name="sortId" ng-model="formData.sortId" ng-minlength="1" ng-maxlength="2" ng-pattern="/^[0-9]*[1-9][0-9]*$/" required/>
                                <label for="inputError" class="control-label text-danger" ng-show="myForm.sortId.$invalid && !myForm.sortId.$pristine"><i class="fa fa-times-circle-o"></i> 请填写1-100以内的整数</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-4">关键字</label>
                            <div class="col-sm-6">
                                <textarea name="keywords" id="" cols="30" class="form-control" rows="4"  ng-model="formData.keywords" ng-minlength="2" ng-maxlength="80" required></textarea>
                                <label for="inputError" class="control-label text-danger" ng-show="myForm.keywords.$invalid && !myForm.keywords.$pristine"><i class="fa fa-times-circle-o"></i>80个字以内，多个关键字之间用逗号隔开</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label col-sm-4">描述</label>
                            <div class="col-sm-7">
                                <textarea name="comments" id="" cols="30" class="form-control" rows="8"  ng-model="formData.comments" ng-minlength="2" ng-maxlength="100" required></textarea>
                                <label for="inputError" class="control-label text-danger" ng-show="myForm.comments.$invalid && !myForm.comments.$pristine"><i class="fa fa-times-circle-o"></i> 2-100个非特殊字符</label>

                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-primary" ng-disabled="myForm.$invalid">提交</button>
                        </div>
                    </form>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->

    </div><!-- /.row -->

</div>


</div>


<script>
    var appModule = angular.module("adminApp",[]);
    appModule.controller('adminCtrl', function ($scope,$http) {
//                初始化模板分类
        iniTreeData($scope,$http);
//        数据初始化
        $scope.warningInfo = {};
        $scope.formData = {};
        $scope.formData.parentID = "0";
//        $scope.formData.defaultUrl = "";

        getData($scope,$http);
        //删除用户
        $('#checkIfDel').on('show.bs.modal', function (event) {
            var obj = $(event.relatedTarget);
            $scope.targetID = obj.data('whatever');
        }).on('hide.bs.modal', function (event) {
            $scope.targetID ="";
        });
        //确认执行删除
        $scope.delCategoryItem = function () {

            if(checkIfPrarent())
            {
                $('#checkIfDel').modal("hide");
                $scope.warningInfo.title = "警告";
                $scope.warningInfo.message = "失败！没有选中节点或该节点下有子节点！"
                $('#askifdo').modal("show");
            }else{
                var currentID =  $scope.targetID;
                $http.get("/admin/manage/contentCategorys/del?uid="+currentID).success(function(result){
                    $('#checkIfDel').modal("hide");
                    console.log("del success!");
                    getData($scope,$http);
                })
            }
        };

//                修改类别
        $('#addContentCategory').on('show.bs.modal', function (event) {
            var obj = $(event.relatedTarget);
            var editId = obj.data('whatever');
            var sortPath = obj.data('array');
            // 继承父类的文件路径
            var homePage = obj.data('homepage');
//            继承父类内容模板
            var contentTemp = obj.data('contenttemp');

            var modalTitle = $(this).find('.modal-title');
//                    如果不为空则为编辑状态
            if(editId){
//                子类不用设置模板，继承父类大类模板
                $("#setCateTemp").addClass("hide");
                $("#defaultUrl").addClass("hide");

                var opt = editId.substring(0,6);
                var currentID = editId.substring(7,editId.length);
//                判断是编辑还是添加子类
                if(opt === "addSub"){
                    $("#defaultUrl").removeClass("hide");
                    modalTitle.text("添加子类");
                    $scope.formData.parentID = currentID;
                    $scope.formData.sortPath = sortPath;
                    $scope.formData.defaultUrl = homePage;
                    $scope.formData.contentTemp = contentTemp;
                    $scope.targetID = "";

                }
                else if(opt === "editNc"){
                    modalTitle.text("编辑分类");
                    $http.get("/admin/manage/contentCategorys/item?uid="+currentID).success(function(result){
                        $scope.formData = result;
                        $scope.targetID = currentID;
                    })
                }
            }else{
                $("#setCateTemp").removeClass("hide");
                $("#defaultUrl").removeClass("hide");
                $("#setCateSort").removeClass("hide")
                modalTitle.text("添加文档类别");
                $scope.formData = {};
                $scope.formData.parentID = "0";
                $scope.formData.sortPath = "0";
            }
        }).on('hidden.bs.modal', function (e) {
            // 清空数据
            $scope.formData = {};
            $scope.targetID ="";
            $(this).find("input").val("");
        });
        //                添加类别
        $scope.processForm = function(isValid){
            var curentUrl = "/admin/manage/contentCategorys/add";
            if($scope.targetID)
            {
                curentUrl = "/admin/manage/contentCategorys/modify?uid="+$scope.targetID;
            }

            if(isValid){
                $http({
                    method  : 'POST',
                    url     : curentUrl,
                    data    : $.param($scope.formData),  // pass in data as strings
                    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  // set the headers so angular passing info as form data (not request payload)
                })
                .success(function(data) {
                    if(data === "success"){
                        $("#addContentCategory").modal("hide");
                        getData($scope,$http);

                    }else{
                        alert("未知异常，请稍后重试");
                    }
                });
            }
            else{
                alert("error");
            }
        }


    });


    function getData($scope,$http){
        $http.get("/admin/manage/contentCategorys/list").success(function(result){

            var arrTree = changeToTreeJson(result);

//            ztree 相关参数设置
            var IDMark_A = "_a";
            var setting = {
                view: {
                    addDiyDom: addDiyDom
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                }
            };

            function addDiyDom(treeId, treeNode) {
                if (treeNode.parentNode && treeNode.parentNode.id != 2) return;
                var aObj = $("#" + treeNode.tId + IDMark_A);
                var editStr = "";
                editStr += "&nbsp;<span id='diyBtn_" +treeNode.id+ "'><a href='#' data-whatever='editNc_" +treeNode.id+ "' class='text-primary' role='button' data-toggle='modal' data-target='#addContentCategory'>编辑</a></span>";
                editStr += "&nbsp;<span id='diyBtn_" +treeNode.id+ "'><a href='#' data-whatever='" +treeNode.id+ "' class='text-primary' role='button' data-toggle='modal' data-target='#checkIfDel'>删除</a></span>";
                editStr += "&nbsp;<span id='diyBtn_" +treeNode.id+ "'><a href='#' data-contenttemp='" +treeNode.contentTemp+ "' data-homepage='" +treeNode.homePage+ "' data-array='" +treeNode.sortPath+ "' data-whatever='addSub_" +treeNode.id+ "' class='text-primary' role='button' data-toggle='modal' data-target='#addContentCategory'>添加子类</a></span>";
                aObj.after(editStr);
            }

            $.fn.zTree.init($("#categoryTree"), setting, arrTree);

        })
    }

//    判断需要删除的节点是否被选中或者是否有子节点
    function checkIfPrarent(){
        var treeObj = $.fn.zTree.getZTreeObj("categoryTree");
        var sNodes = treeObj.getSelectedNodes();
        if (sNodes.length > 0) {
            var isParent = sNodes[0].isParent;
            if(isParent){
                return true;
            }
            else{
                return false;
            }
        }else{
            return true;
        }
    }


    function iniTreeData($scope,$http){
        $http.get("/admin/manage/contentTemps/list").success(function(result){
            var tempsName = $("#tempsName");
            tempsName.html(getCateNameById(result,$scope.formData.contentTemp));
            var arrTree = changeToTreeJson(result,"temps");
            var setting = {
                view: {
                    dblClickExpand: false,
                    selectedMulti: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    beforeClick: beforeClick,
                    onClick: onClick
                }
            };

            function beforeClick(treeId, treeNode) {
                var check = (treeNode && !treeNode.isParent);
                if (!check) alert("不能选择顶级分类");
                return check;
            }

            function onClick(e, treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                        nodes = zTree.getSelectedNodes(),
                        v = "",
                        vid = "";

                nodes.sort(function compare(a,b){return a.id-b.id;});
                for (var i=0, l=nodes.length; i<l; i++) {
                    v += nodes[i].name ;
                    vid += nodes[i].alias ;
                }

                tempsName.html(v);
                $scope.formData.contentTemp = vid;

            }

            $.fn.zTree.init($("#treeDemo"), setting, arrTree);
        })
    }

</script>